package com.zzq.controller.v2;


import com.zzq.model.v2.pod.CreatePodEntity;
import com.zzq.model.v2.pod.SearchPodEntity;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.kubernetes.client.StringUtil;
import io.sundr.codegen.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/new/pod")
@RestController
@Slf4j
public class NewPodController {


    @Autowired
    private KubernetesClient client;

    /**
     * 创建pod
     * @param createPodEntity
     * @return
     */
    @PostMapping(value = "/create")
    public Boolean createPod(@RequestBody CreatePodEntity createPodEntity){
        try {
            Pod pod = new PodBuilder()
                    .withNewMetadata()
                    .withNamespace(createPodEntity.getNamespace())
                    .withName(createPodEntity.getName())
                    .withLabels(createPodEntity.getLabels())
                    .endMetadata()
                    .withNewSpec()
                    .withContainers(createPodEntity.getContainers())
                    .endSpec()
                    .build();
            Pod podRes = client.pods()
                    .create(pod);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建pod失败",e);
            return false;
        }
        return true;
    }


    /**
     * 获取pod
     * @param searchPodEntity
     * @return
     */
    @PostMapping(value = "/list")
    public List<Pod> listPod(@RequestBody SearchPodEntity searchPodEntity){
        PodFluent.MetadataNested<PodBuilder> podBuilderMetadataNested = new PodBuilder()
                .withNewMetadata();
        if(!StringUtils.isNullOrEmpty(searchPodEntity.getNamespace())){
            podBuilderMetadataNested = podBuilderMetadataNested
                    .withNamespace(searchPodEntity.getNamespace());
        }

        if(!StringUtils.isNullOrEmpty(searchPodEntity.getName())){
            podBuilderMetadataNested = podBuilderMetadataNested
                    .withName(searchPodEntity.getName());
        }

        if(!CollectionUtils.isEmpty(searchPodEntity.getLabels())){
            podBuilderMetadataNested = podBuilderMetadataNested
                    .withLabels(searchPodEntity.getLabels());
        }
        podBuilderMetadataNested.endMetadata()
                .build();
        List<Pod> items = client.pods().list().getItems();
        return items;
    }
}
